import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { loginAPI } from '@/api/user'
import { useLocalCartStore } from './localCart'

export const useUserStore = defineStore(
  'user',
  () => {
    const localCart = useLocalCartStore()
    // 提供state
    const userInfo = ref({})

    // 提供getter
    const token = computed(() => userInfo.value.token)

    // 提供action
    // 登录接口
    const setUserInfo = async (data) => {
      const res = await loginAPI(data)
      userInfo.value = res.result

      // 合并本地购物车与服务器购物车，并获取购物车列表
      await localCart.mergeCart()
      await localCart.setCartList()
    }

    // 登出接口
    const removeUserInfo = () => {
      userInfo.value = {}
      localCart.clearCart()
    }

    return {
      userInfo,
      token,
      setUserInfo,
      removeUserInfo
    }
  },
  {
    persist: true
  }
)
